<template>
    <div class="friends-container">
        <div class="header-section">
            <el-page-header @back="goBack" title="返回">
                <template #content>
                    <h2>好友管理</h2>
                </template>
            </el-page-header>

            <div class="friend-tabs">
                <el-tabs v-model="activeTab">
                    <el-tab-pane label="好友请求" name="requests"></el-tab-pane>
                    <el-tab-pane label="我的好友" name="friends"></el-tab-pane>
                    <el-tab-pane label="可能认识的人" name="recommendations"></el-tab-pane>
                </el-tabs>
            </div>
        </div>

        <el-divider />

        <div class="content-section">
            <div v-if="activeTab === 'requests'">
                <div class="request-header">
                    <el-button type="primary" icon="Refresh" @click="refreshRequests" :loading="isLoading">
                        刷新
                    </el-button>
                    <span class="count">共 {{ requests.length }} 条请求</span>
                </div>

                <div v-if="requests.length === 0" class="empty-requests">
                    <el-empty description="暂无好友请求" />
                </div>

                <div v-else class="request-list">
                    <div v-for="request in requests" :key="request.ufId" class="request-item">
                        <div class="request-user">
                            <el-avatar :size="50" :src="request.fromAvatarUrl || defaultAvatar" />
                            <div class="user-info">
                                <div class="username">{{ request.fromNickname || request.fromUsername }}</div>
                                <div class="time">{{ formatTime(request.createTime) }}</div>
                            </div>
                        </div>
                        <div class="request-actions">
                            <el-button type="success" @click="handleRespond(request.ufId, true)"
                                :loading="loadingMap[request.ufId]?.accept">
                                接受
                            </el-button>
                            <el-button type="danger" @click="handleRespond(request.ufId, false)"
                                :loading="loadingMap[request.ufId]?.reject">
                                拒绝
                            </el-button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 我的好友面板 -->
            <div v-if="activeTab === 'friends'">
                <div class="friends-header">
                    <h3>我的好友 ({{ friends.length }})</h3>
                    <el-button type="primary" :icon="Refresh" @click="fetchFriends" :loading="friendsLoading" circle />
                </div>

                <div v-if="!friendsLoading" class="friends-content">
                    <div v-if="friends.length === 0" class="empty-friends">
                        <el-empty description="暂无好友" />
                    </div>

                    <div v-else class="friends-grid">
                        <div v-for="friend in friends" :key="friend.userId" class="friend-card">
                            <div class="card-header">
                                <el-avatar :size="60" :src="friend.avatarUrl || defaultAvatar" />
                                <div class="basic-info">
                                    <div class="name">
                                        {{ friend.nickname || friend.username }}
                                        <el-tag :type="friend.gender === 1 ? '' : 'danger'" size="small">
                                            {{ friend.gender === 1 ? '男' : '女' }}
                                        </el-tag>
                                    </div>
                                    <div class="contact">
                                        <span v-if="friend.userPhone">
                                            <el-icon>
                                                <Iphone />
                                            </el-icon> {{ friend.userPhone }}
                                        </span>
                                        <span v-if="friend.email">
                                            <el-icon>
                                                <Message />
                                            </el-icon> {{ friend.email }}
                                        </span>
                                    </div>
                                </div>
                            </div>

                            <div class="card-details">
                                <div class="detail-item" v-if="friend.educationInfo">
                                    <el-icon>
                                        <School />
                                    </el-icon>
                                    <span>{{ friend.educationInfo }}</span>
                                </div>
                                <div class="detail-item" v-if="friend.workInfo">
                                    <el-icon>
                                        <Briefcase />
                                    </el-icon>
                                    <span>{{ friend.workInfo }}</span>
                                </div>
                                <div class="detail-item" v-if="friend.locationInfo">
                                    <el-icon>
                                        <Location />
                                    </el-icon>
                                    <span>{{ friend.locationInfo }}</span>
                                </div>
                            </div>
                            <div class="card-actions">
                                <el-button type="primary" size="small" @click="sendMessage(friend.userId)" plain>
                                    <el-icon>
                                        <ChatDotRound />
                                    </el-icon>
                                    <span>私信</span>
                                </el-button>
                            </div>
                        </div>
                    </div>
                </div>

                <div v-else class="friends-loading">
                    <el-icon class="is-loading" :size="30">
                        <Loading />
                    </el-icon>
                    加载中...
                </div>
            </div>

            <!-- 可能认识的人面板 -->
            <div v-if="activeTab === 'recommendations'" class="recommend-container">
                <div v-if="isRecommendLoading" class="loading-container">
                    <el-skeleton :rows="5" animated />
                </div>

                <el-alert v-else-if="recommendError" :title="recommendError" type="error" show-icon closable @close="recommendError = null" />

                <template v-else>
                    <div v-if="recommendations.length === 0" class="empty-tip">
                        <el-empty description="填写详细的社交信息，为您推荐更多可能认识的人哦~" />
                    </div>

                    <div v-else class="recommend-list">
                        <RecommendUserCard v-for="user in recommendations" :key="user.userId" :user="user" />
                    </div>

                    <div class="load-more">
                        <el-button type="primary" :loading="isRecommendLoading" @click="loadMore" v-if="recommendations.length >= recommendLimit">
                            加载更多
                        </el-button>
                    </div>
                </template>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useSocialStore } from '@/stores/modules/social/social';
import { respondToFriendRequest } from '@/api/social';
import { ElMessage } from 'element-plus';
import defaultAvatar from '@/assets/default-avatar.png';
import dayjs from 'dayjs';
import { useUserStore } from "@/stores";
import {
    Refresh, Iphone, Message,
    School, Briefcase, Location, Loading,ChatDotRound
} from '@element-plus/icons-vue';
import type { UserDto } from '@/api/types';
import { getMyFriends } from '@/api/social';
import RecommendUserCard from '@/components/social/RecommendUserCard.vue';

const userStore = useUserStore();
const router = useRouter();
const socialStore = useSocialStore();

// 好友请求相关状态
const activeTab = ref('requests');
interface LoadingMap {
    [key: number]: {
        accept: boolean;
        reject: boolean;
    };
}

const loadingMap = reactive<LoadingMap>({});
const isLoading = computed(() => socialStore.isLoading);
const requests = computed(() => socialStore.friendRequests);

// 我的好友相关状态
const friends = ref<UserDto[]>([]);
const friendsLoading = ref(false);

// 可能认识的人相关状态
const isRecommendLoading = computed(() => socialStore.isLoading);
const recommendError = computed(() => socialStore.error);
const recommendations = computed(() => socialStore.recommendations || []);
const recommendLimit = ref(9);

// 格式化时间
const formatTime = (time: string | null | undefined) => {
    if (!time) return '未知时间';
    return dayjs(time).format('YYYY-MM-DD HH:mm');
};

// 刷新好友请求列表
const refreshRequests = async () => {
    await socialStore.fetchFriendRequests(userStore.currentUser.userId);
};

// 处理接受或拒绝好友请求
const handleRespond = async (requestId: number, accept: boolean) => {
    if (!loadingMap[requestId]) {
        loadingMap[requestId] = { accept: false, reject: false };
    }

    const key = accept ? 'accept' : 'reject';
    loadingMap[requestId][key] = true;

    try {
        await respondToFriendRequest(requestId, accept, userStore.currentUser.userId);
        ElMessage.success(accept ? '已接受好友请求' : '已拒绝好友请求');
        await refreshRequests();
    } catch (err: any) {
        ElMessage.error(err.message || '操作失败');
    } finally {
        loadingMap[requestId][key] = false;
    }
};

// 我的好友相关方法
const fetchFriends = async () => {
    try {
        friendsLoading.value = true;
        friends.value = await getMyFriends(userStore.currentUser.userId);
    } catch (error) {
        ElMessage.error('获取好友列表失败');
        console.error(error);
    } finally {
        friendsLoading.value = false;
    }
};

// 可能认识的人相关方法
const fetchRecommendations = async () => {
    await socialStore.fetchRecommendations(recommendLimit.value, userStore.currentUser.userId);
};

const loadMore = () => {
    recommendLimit.value += 5;
    fetchRecommendations();
};

const goBack = () => {
    router.go(-1);
};

onMounted(() => {
    refreshRequests();
    fetchFriends();
    fetchRecommendations();
});

//待办 私信功能
const sendMessage = (userId: number) => {
    console.log('发送私信给用户:', userId);
    ElMessage.success('私信功能有待开发哦！');
};
</script>

<style scoped>
.friends-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
}

.header-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.friend-tabs {
    flex: 1;
    margin-left: 40px;
}

:deep(.el-tabs__header) {
    margin: 0;
}

:deep(.el-tabs__nav-wrap) {
    padding-left: 20px;
}

.content-section {
    margin-top: 20px;
}

.request-header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    gap: 16px;
}

.count {
    color: var(--el-text-color-secondary);
    font-size: 14px;
}

.request-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.request-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    border-radius: 4px;
    background-color: var(--el-fill-color-light);
}

.request-user {
    display: flex;
    align-items: center;
}

.user-info {
    margin-left: 12px;
}

.username {
    font-weight: 500;
}

.time {
    font-size: 12px;
    color: var(--el-text-color-secondary);
}

.request-actions {
    display: flex;
    gap: 8px;
}

.empty-requests {
    padding: 40px 0;
}

.friends-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.friends-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 20px;
    margin-top: 20px;
}

.friend-card {
    background: #fff;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    transition: all 0.3s ease;
    border: 1px solid var(--el-border-color-light);
    display: flex;
    flex-direction: column;
    height: 100%;
}

.friend-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
}

.card-header {
    display: flex;
    padding: 20px;
    align-items: center;
    background: linear-gradient(135deg, #f6f7f9 0%, #e9ebee 100%);
    border-bottom: 1px solid var(--el-border-color-light);
}

.card-header .el-avatar {
    border: 3px solid #fff;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.basic-info {
    margin-left: 15px;
    flex: 1;
}

.basic-info .name {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 5px;
    display: flex;
    align-items: center;
    gap: 8px;
}

.basic-info .contact {
    font-size: 12px;
    color: var(--el-text-color-secondary);
    display: flex;
    flex-direction: column;
    gap: 4px;
}

.basic-info .contact span {
    display: flex;
    align-items: center;
    gap: 5px;
}

.card-details {
    padding: 15px 20px;
    flex: 1;
}

.detail-item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    font-size: 13px;
    color: var(--el-text-color-regular);
}

.detail-item:last-child {
    margin-bottom: 0;
}

.detail-item .el-icon {
    margin-right: 8px;
    color: var(--el-color-primary);
}

.friends-loading {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 40px 0;
    color: var(--el-text-color-secondary);
    gap: 10px;
}

.friends-loading .el-icon {
    animation: rotating 2s linear infinite;
}

.card-actions {
    padding: 0 20px 20px;
    margin-top: auto;
    display: flex;
    justify-content: flex-end;
}

.card-actions .el-button {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    border-radius: 16px;
    padding: 6px 12px;
}

/* 可能认识的人样式 */
.recommend-container {
    height: 100%;
    /* overflow: scroll; */
}

.loading-container {
    padding: 20px 0;
}

.recommend-list {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 16px;
}

.load-more {
    margin-top: 24px;
    text-align: center;
}

.empty-tip {
    margin-top: 40px;
}

@keyframes rotating {
    from {
        transform: rotate(0deg);
    }

    to {
        transform: rotate(360deg);
    }
}

@media (max-width: 768px) {
    .friends-grid {
        grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
    }

    .header-section {
        flex-direction: column;
        align-items: flex-start;
    }

    .friend-tabs {
        margin-left: 0;
        margin-top: 15px;
        width: 100%;
    }
}

@media (max-width: 480px) {
    .friends-grid {
        grid-template-columns: 1fr;
    }

    .friend-card {
        max-width: 100%;
    }

    .card-actions .el-button span {
        display: none;
    }
    
    .card-actions .el-button {
        padding: 6px 8px;
    }
}
</style>